<template>
  <div class="search" :style="{ '--themeColor': themeColor }">
    <NavBar title="门店列表" />
    <div class="head">
      <div class="input">
        <u-search
          shape="round"
          :focus="isFocus"
          bgColor="#fff"
          clearabled
          v-model="queryParams.shopName"
          searchIconSize="26"
          maxlength="10"
          @search="searchShop"
          @custom="searchShop"
          @focus="showHistory = true"
          placeholder="请输入搜索内容"
        />
      </div>
      <div class="select" v-if="!showHistory">
        <div class="left-title">全部门店</div>
        <div class="right">
          <div
            :class="['one', queryParams.sortType == index ? 'active' : '']"
            v-for="(item, index) in filterItems"
            :key="index"
            @click="changeSelect(index)"
          >
            {{ item }}
          </div>
        </div>
      </div>
    </div>
    <div class="histoy" v-if="showHistory">
      <div class="top">
        <div class="title">历史搜索</div>
        <u-icon
          name="trash"
          color="#888888"
          size="24"
          @click="clearHistory"
        ></u-icon>
      </div>
      <div class="list">
        <div
          class="one"
          v-for="item in historyList"
          :key="item"
          @click="setSearch(item)"
        >
          {{ item }}
        </div>
      </div>
    </div>
    <div class="shop-list" v-show="showHistory == false">
      <mescroll-uni
        :fixed="false"
        ref="mescrollRef"
        @down="downCallback"
        @up="upCallback"
        :up="{
          textNoMore: '没有更多了',
          empty: {
            tip: '暂无相关数据',
            icon: 'https://hyyxboss.oss-cn-shenzhen.aliyuncs.com//img/pub/no_data.png',
            fixed: true,
            top: '40%',
          },
        }"
      >
        <div
          v-for="(item, index) in dataList"
          :key="item.id"
          class="shop-content"
          @click="toShop(item.id)"
        >
          <div class="img">
            <xhImg :src="item.logo" />
          </div>
          <div class="msg">
            <div class="top">
              <div class="title">{{ item.name }}</div>
              <div class="detail">
                <div class="left">
                  <div :class="['falg', item.isOpen ? 'open' : '']">
                    {{ item.isOpen ? "营业中" : "休息中" }}
                  </div>
                  <div class="type">{{ industryType[item.shopType] }}</div>
                  <div class="month">月售{{ item.monthSales }}</div>
                </div>
                <div class="distance" v-if="item.distance">
                  {{ $myTool.transitionDistance(item.distance) }}
                </div>
              </div>
            </div>

            <div class="store-val" v-if="item.balanceActivityDesc">
              {{ item.balanceActivityDesc }}
            </div>
          </div>
        </div>
      </mescroll-uni>
    </div>
  </div>
</template>

<script>
import MescrollMixin from "@/uni_modules/mescroll-uni/components/mescroll-uni/mescroll-mixins.js";
import multistepFilter from "@/components/pageComponents/sp-store/multistepFilter";
import { getShops } from "@/service/api/sp-store/index";
import { mapState } from "vuex";
export default {
  mixins: [MescrollMixin], // 使用mixin
  data() {
    return {
      historyList: [],
      goodsHistory: {},
      showHistory: false,
      isFocus: false,
      dataList: [],
      queryParams: {
        latitude: "",
        longitude: "",
        shopName: "",
        // 门店类型 1餐饮；2便利店；3休闲娱乐；4美容美发， 不传则查全部类型
        // shopType: "",
        // 排序规则 1综合排序 2距离优先 3人气优先
        sortType: 1,
        pageNum: 1,
        pageSize: 10,
        pubDomainBusinessId: "",
      },
      dataList: [],
      filterItems: {
        1: "综合排序",
        2: "距离优先",
        3: "人气优先",
      },
    };
  },
  computed: {
    ...mapState("sp-common/base", ["themeColor"]),
    ...mapState("sp-store/index", ["industryType"]),

  },
  components: {
    multistepFilter,
  },
   onReady() {
    this?.$Route?.query?.shopId?(this.isFocus = false) : "";
    this.queryParams.pubDomainBusinessId = this?.$Route?.query?.shopId;
    this.getHistory();
    this.getUserLocation();
  },
  onUnload() {
    this.setHistory();
  },
  methods: {
    searchShop() {
      let {
        historyList,
        queryParams: { shopName },
      } = this;
      if (!shopName) return;
      if (historyList.indexOf(shopName) !== -1) {
        historyList.splice(historyList.indexOf(shopName), 1);
      }
      this.historyList.unshift(shopName);
      if (historyList.length == 9) this.historyList.pop();
      this.showHistory = false;
      this.mescroll.resetUpScroll();
    },
    getHistory() {
      uni.getStorage({
        key: "publicShopHistory",
        success: (res) => {
          this.goodsHistory = JSON.parse(res.data);
          this.historyList = this.goodsHistory || [];
        },
      });
    },
    setHistory() {
      let { historyList } = this;
      uni.setStorage({
        key: "publicShopHistory",
        data: JSON.stringify(historyList),
      });
    },
    clearHistory() {
      this.historyList = [];
    },
    setSearch(item) {
      this.queryParams.shopName = item;
      this.searchShop();
    },
    changeSelect(val) {
      this.queryParams.sortType = val;
      this.mescroll.resetUpScroll();
    },
    fetData() {
      let {
        queryParams,
        queryParams: { pageNum },
      } = this;
      getShops(queryParams)
        .then((res) => {
          let { total, list = [] } = res;
          if (pageNum == 1) this.dataList = [];
          if (!list) list = [];
          this.mescroll.endBySize(list.length || 0, total);
          this.dataList =
            pageNum == 1 ? list || [] : this.dataList.concat(list);
          this.showHistory = false;
        })
        .catch((res) => {
          console.log(res);
          this.mescroll.endErr();
          this.showHistory = false;
        });
    },
    downCallback(page) {
      this.queryParams.pageNum = 1;
      this.mescroll.resetUpScroll();

    },
    upCallback(page) {
      this.queryParams.pageNum = page.num;
      this.fetData();
    },
    getUserLocation() {
      let {
        queryParams: { longitude, latitude },
      } = this;
      if (!longitude || !latitude) {
        this.$getUserLocation()
          .then((res) => {
            let result = res?.currentLocation
              ? res?.currentLocation
              : res?.location;
            let { longitude, latitude } = result;
            this.queryParams = Object.assign({}, this.queryParams, {
              longitude,
              latitude,
            });
            this.mescroll.resetUpScroll();
          })
          .catch(() => {
            this.mescroll.endErr();
          });
        return;
      }
    },
    toShop(id) {
      const eventChannel = this.getOpenerEventChannel();
      eventChannel.emit("acceptDataFromOpenedPage", { shopId: id });
      this.$myTool.jumpPage("back");
    },
  },
};
</script>

<style lang="scss" scoped>
@import "@/pages/sp-store/css/shop-search.scss";
.select {
  display: flex;
  width: calc(100% - 100rpx);
  margin: 0 auto;
  padding: 20rpx 50rpx;
  background: #f7f7f7;
  .left-title {
    font-size: 32rpx;
    font-family: PingFang SC;
    font-weight: bold;
    color: #181818;
  }
  .right {
    flex: 1;
    display: flex;
    justify-content: flex-end;
    .one {
      font-size: 28rpx;
      font-family: PingFang SC;
      font-weight: 500;
      color: #181818;
      margin-left: 40rpx;
    }
    .active {
      color: var(--theme-color) !important;
    }
  }
}
</style>
